<template>
  <div class="app-container">
    <el-container>
      <el-aside width="width:100%">
        <el-row v-for="spot in cardData.maxSpot+1" :key="spot">
          <el-col v-for="lane in cardData.maxLane+1" :key="lane" style="width: 150px;height:70px">
            <el-card v-if="spot === 1 || lane === 1" shadow="never" class="box-card">
              <div v-if="spot === 1 && lane === 1">{{ 'spot / lane' }}</div>
              <div v-if="spot === 1 && lane !== 1">{{ lane - 1 }}</div>
              <div v-if="spot !== 1 && lane === 1">{{ spot - 1 }}</div>
            </el-card>
            <el-card v-else-if="!cardData.items[spot-1][lane-1].id" shadow="hover" class="box-card">
              <div :style="{'color': getCardContentColor(cardData.items[spot-1][lane-1])}"> - </div>
            </el-card>
            <el-popover
              v-else
              placement="right-end"
              width="250"
              trigger="click"
              @show="cardPopoverShow">
              <div>
                <span>{{ cardData.items[spot-1][lane-1].driverName }}</span>
                <el-tooltip :content="$t('BookStore2[\'ConfirmLineUp\']')" placement="top" effect="light">
                  <el-button style="float: right; padding: 0;font-size: 20px;color:red" icon="el-icon-check" type="text" @click="confirmLineUp(cardData.items[spot-1][lane-1])"></el-button>
                </el-tooltip>
                <el-tooltip :content="$t('BookStore2[\'NoticeLineUp\']')" placement="top" effect="light">
                  <el-button style="float: right; padding: 0;font-size: 20px;color:red" icon="el-icon-bell" type="text" @click="noticeLineUp(cardData.items[spot-1][lane-1])"></el-button>
                </el-tooltip>
                <el-tooltip :content="$t('BookStore2[\'SwitchDriver\']')" placement="top" effect="light">
                  <el-button style="float: right; padding: 0;font-size: 20px" icon="el-icon-user" type="text" @click="openSwitchDriverDialog(cardData.items[spot-1][lane-1])"></el-button>
                </el-tooltip>
                <el-divider></el-divider>
                <div style="text-align:center;padding-bottom: 6px">{{ $t('BookStore2[\'' + cardData.items[spot-1][lane-1].registerVehicleBrand + '\']') }}</div>
                <div style="text-align:center;padding-bottom: 6px">{{ cardData.items[spot-1][lane-1].registerVehicle }}</div>
                <div style="text-align:center;padding-bottom: 6px">{{ cardData.items[spot-1][lane-1].route }}</div>
                <div style="text-align:center;padding-bottom: 6px">{{ cardData.items[spot-1][lane-1].stage }}</div>
                <div style="text-align:center;padding-bottom: 6px">{{ 'L ' + cardData.items[spot-1][lane-1].lane + '-' + cardData.items[spot-1][lane-1].spot }}</div>
              </div>
              <el-card slot="reference" shadow="hover" :style="{'background-color': getCardBackgroundColor(cardData.items[spot-1][lane-1])}" class="box-card">
                <div :style="{'color': getCardContentColor(cardData.items[spot-1][lane-1])}">{{ getCardContent(cardData.items[spot-1][lane-1]) }}</div>
              </el-card>
            </el-popover>
          </el-col>
        </el-row>
      </el-aside>
      <el-main>
        <div>
          <span style="margin-bottom: 3px;">{{ $t('BookStore2[\'Status\']') + ': ' }}</span>
          <el-tag class="status-tag" style="background-color:#909399;">{{ $t('BookStore2[\'Enum:TrafficDispatchTaskItemStatus:1\']') }}</el-tag>
          <el-tag class="status-tag" style="background-color:#ffba00;">{{ $t('BookStore2[\'Enum:TrafficDispatchTaskItemStatus:2\']') }}</el-tag>
          <el-tag class="status-tag" style="background-color:#13ce66;">{{ $t('BookStore2[\'Enum:TrafficDispatchTaskItemStatus:3\']') }}</el-tag>
          <el-tag class="status-tag" style="background-color:#e64242;">{{ $t('BookStore2[\'Enum:TrafficDispatchTaskItemStatus:4\']') }}</el-tag>
        </div>
        <el-divider></el-divider>
        <span style="margin-bottom: 3px;">{{ $t('BookStore2[\'Action\']') + ': (' +  $t('BookStore2[\'Enum:TrafficDispatchTaskStatus:' + trafficDispatchTask.currentStatus + '\']') + ')' }}</span>
        <el-button v-show="trafficDispatchTask.currentStatus === 1" class="btn-execute" style="background-color: #13ce66;" icon="el-icon-video-play" @click="executeTask(2)">{{ $t('BookStore2[\'Run\']') }}</el-button>
        <el-button v-show="trafficDispatchTask.currentStatus === 2" class="btn-execute" style="background-color: #e6b000;" icon="el-icon-video-pause" @click="executeTask(3)">{{ $t('BookStore2[\'Pause\']') }}</el-button>
        <el-button v-show="trafficDispatchTask.currentStatus === 3" class="btn-execute" style="background-color: #13ce66;" icon="el-icon-video-play" @click="executeTask(2)">{{ $t('BookStore2[\'Continue\']') }}</el-button>
<!--        <el-button class="btn-execute" style="background-color: #13ce66;" icon="el-icon-video-play" @click="executeTask(4)">{{ $t('BookStore2[\'Discontinue\']') }}</el-button>-->
        <el-divider></el-divider>
        <el-form :inline="true" @submit.native.prevent>
          <el-form-item :label="$t('BookStore2[\'RefreshInterval\']')">
            <el-input v-model.number="timeout" class="edit-input" size="small" />
          </el-form-item>
        </el-form>
        <el-button v-if="!openTimer" class="btn-auto-fresh" style="background-color: #13ce66;" icon="el-icon-video-play" @click="openInterval">{{ $t('BookStore2[\'AutoFresh\']') }}</el-button>
        <el-button v-else class="btn-auto-fresh" style="background-color: #e6b000;" icon="el-icon-video-pause" @click="closeInterval">{{ $t('BookStore2[\'AutoFresh\']') }}</el-button>
        <el-button class="btn-execute" type="primary" icon="el-icon-refresh" @click="fetchData"></el-button>
      </el-main>
    </el-container>
    <el-dialog
      :title="$t('BookStore2[\'SwitchDriver\']')"
      :visible.sync="switchDriverDialogVisible"
      width="30%"
      :before-close="closeSwitchDriverDialog"
    >
      <el-select v-model="switchDriverForm.driver" style="width: 100%;" filterable clearable>
        <el-option v-for="item in unSelectedUserList" :key="item.id" :label="item.name + ' ' + item.surname + ' ( ' + item.userName + ' ) '" :value="item.id" />
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeSwitchDriverDialog">{{$t('BookStore2[\'Cancel\']')}}</el-button>
        <el-button type="primary" @click="switchDriver">{{$t('BookStore2[\'Ok\']')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getById, noticeLineUp, executeTask, confirmLineUp, switchDriver } from '@/api/trafficDispatch/trafficDispatchTask'
import { getList as getUserList } from '@/api/administration/user/user'
export default {
  name: 'TrafficDispatchTaskItem',
  props: ['trafficDispatchTaskId'],
  data() {
    return {
      trafficDispatchTask: {
        currentStatus: 1
      },
      listLoading: false,
      cardData: {
        laneSpan: 1,
        maxSpot: 0,
        maxLane: 0,
        items: []
      },
      cardPopoverTitle: '',
      connection: null,
      switchDriverDialogVisible: false,
      unSelectedUserList: [],
      switchDriverForm: {
        driver: null,
        itemId: null,
        id: null
      },
      timeout: 5, // 5秒
      timer: null,
      openTimer: false
    }
  },
  async created() {
    this.fetchData()
    this.unSelectedUserList = (await getUserList()).items
    // this.openInterval()
  },
  destroyed() {
    this.closeInterval()
  },
  methods: {
    openInterval() {
      if (this.timeout < 5) {
        this.$message({
          message: this.$t('BookStore2[\'TimeIntervalMustGreaterThan{0}Seconds\']', [5]),
          type: 'error'
        })
        return
      }
      if (this.timer) {
        this.closeInterval()
      }
      this.timer = window.setInterval(() => {
        setTimeout(this.fetchData, 0)
      }, this.timeout * 1000)
      this.openTimer = true
    },
    closeInterval() {
      window.clearInterval(this.timer)
      this.openTimer = false
    },
    fetchData() {
      this.listLoading = true
      getById(this.trafficDispatchTaskId).then((response) => {
        this.trafficDispatchTask = response

        // 默认行列数
        this.cardData.maxLane = 5
        this.cardData.maxSpot = 10
        // 构造数据表格
        if (response.trafficDispatchTaskItems) {
          const taskItemDict = {}
          response.trafficDispatchTaskItems.forEach(item => {
            // 计算最大列
            if (item.lane > this.cardData.maxLane) {
              this.cardData.maxLane = item.lane
            }
            // 计算最大行
            if (item.spot > this.cardData.maxSpot) {
              this.cardData.maxSpot = item.spot
            }
            // 按lane+spot构造字典
            taskItemDict[item.lane + '-' + item.spot] = item
          })

          // 初始化二维数组
          for (let i = 0; i <= this.cardData.maxSpot; i++) {
            this.cardData.items[i] = []
            for (let j = 0; j <= this.cardData.maxLane; j++) {
              this.cardData.items[i][j] = {}
            }
          }

          // 填充数据到二维数组
          for (const key in taskItemDict) {
            const keySplits = key.split('-')
            const lane = keySplits[0]
            const spot = keySplits[1]
            this.cardData.items[parseInt(spot)][parseInt(lane)] = taskItemDict[key]
          }
        }
        this.listLoading = false
      })
    },
    getCardContent(item) {
      if (item.id) {
        return item.registerVehicle
      } else {
        return '-'
      }
    },
    getCardBackgroundColor(item) {
      if (item.id) {
        switch (item.currentStatus) {
          case 1: // 等待排队
            return '#909399'
          case 2: // 排队未确认
            return '#ffba00'
          case 3: // 排队已确认
            return '#13ce66'
          case 4: // 暂停
            return '#e64242'
        }
      }
    },
    getCardContentColor(item) {
      if (item.id) {
        return '#ffffff'
      }
    },
    cardPopoverShow() {
    },
    async noticeLineUp(item) {
      await noticeLineUp({
        userId: item.driver,
        trafficDispatchTaskId: item.trafficDispatchTaskId
      })
      this.$message({
        message: this.$t('BookStore2[\'Ok\']'),
        type: 'success'
      })
    },
    async executeTask(status) {
      await executeTask(this.trafficDispatchTaskId, status)
      this.$message({
        message: this.$t('BookStore2[\'Ok\']'),
        type: 'success'
      })
      this.fetchData()
    },
    async confirmLineUp(item) {
      await confirmLineUp({
        userId: item.driver,
        trafficDispatchTaskId: item.trafficDispatchTaskId
      })
      this.$message({
        message: this.$t('BookStore2[\'Ok\']'),
        type: 'success'
      })
      this.fetchData()
    },
    openSwitchDriverDialog(item) {
      this.switchDriverForm.itemId = item.id
      this.switchDriverForm.id = this.trafficDispatchTaskId
      this.switchDriverDialogVisible = true
    },
    closeSwitchDriverDialog() {
      this.clearSwitchDriverForm()
      this.switchDriverDialogVisible = false
    },
    clearSwitchDriverForm() {
      this.switchDriverForm.itemId = null
      this.switchDriverForm.id = null
      this.switchDriverForm.driver = null
    },
    async switchDriver() {
      await switchDriver(this.switchDriverForm.id, this.switchDriverForm.itemId, this.switchDriverForm.driver)
      this.$message({
        message: this.$t('BookStore2[\'Ok\']'),
        type: 'success'
      })
      this.closeSwitchDriverDialog()
      this.fetchData()
    }
  }
}
</script>

<style lang="scss" scoped>

.status-tag {
  font-size:15px;
  text-align: center;
  line-height: 28px;
  width: 100px;
  height: 30px;
  color: #ffffff;
  margin-right:5px;
}

.btn-execute {
  font-size: 15px;
  color: #ffffff;
  width: 120px;
  height: 40px;
}

.btn-auto-fresh {
  font-size: 15px;
  color: #ffffff;
  width: 150px;
  height: 40px;
}

</style>

